package com.yl.chainStore.payrule.order.service


import com.yl.chainStore.entity.pay.PayCustomerOrder
import com.yl.chainStore.entity.pay.PayCustomerOrderDiscountLog
import com.yl.chainStore.entity.pay.PayCustomerOrderItemDiscountRuleLog
import com.yl.chainStore.payrule.common.DiscountComputeOrderResultVo
import com.yl.chainStore.payrule.item.entity.BuyAndDiscountRule
import com.yl.chainStore.payrule.order.OrderRuleService
import com.yl.chainStore.payrule.order.OrderRuleTypeEnum
import com.yl.chainStore.payrule.order.entity.OrderFullMoneySendMoneyRule
import com.yl.chainStore.services.IWebCompanyDeptService
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service

@Service
class OrderFullMoneySendMoneyRuleServiceImpl: OrderRuleService {

	@Autowired
	private lateinit var iWebCompanyDeptService: IWebCompanyDeptService

	private val ruleType = OrderRuleTypeEnum.ORDER_FULL_MONEY_SEND_MONEY


	override fun computeOrder(order: PayCustomerOrder): DiscountComputeOrderResultVo {
		val ruleList =
			iWebCompanyDeptService.getNowOpenOrderDiscountRuleList(getContext().subCompanyId, ruleType)


		if(order.details != null && order.details!!.isNotEmpty()){
			for(orderRule in ruleList){
				val rule = orderRule.getOtherContentObj() as OrderFullMoneySendMoneyRule
				if(rule.canUseForOrder(order)){
					//可以使用
					var discountMoney = rule.disCountMoney
					val originalPrice = order.amountMoney
					if(order.originalPrice < rule.disCountMoney){
						order.originalPrice = 0
						discountMoney = originalPrice
					}else{
						order.originalPrice = order.originalPrice - rule.disCountMoney
					}
					if(order.details != null){
						for(d in order.details!!){
							d.realMoney = d.realMoney.times(order.originalPrice).div(originalPrice)
							d.realPrice = d.realMoney.div(d.number)
						}
					}
					order.addPayCustomerOrderDiscountLog(PayCustomerOrderDiscountLog(
						id = 0,
						orderId = order.id,
						customerId = order.customerId,
						createUserId = getContext().userId,
						ruleId = orderRule.id,
						content = orderRule.title,
						discountMoney = discountMoney
					))

				}

			}
		}
		return DiscountComputeOrderResultVo(returnSuccess(),order)
	}
}


